home *** CD-ROM | disk | FTP | other *** search
- Path: atglab.bls.com!Alun.Champion
- From: Alun.Champion@bridge.bst.bls.com (Alun Champion)
- Newsgroups: comp.lang.c
- Subject: Re: Can a function return a (pointer to a) function?
- Date: 26 Jan 1996 23:14:42 GMT
- Organization: Computer People Inc.
- Message-ID: <ALUN.CHAMPION.96Jan26181442@g7240065.bridge.bst.bls.com>
- References: <4ebaaa$jh6@barnacle.iol.ie>
- NNTP-Posting-Host: bstfirewall.bst.bls.com
- In-reply-to: "John D. Hourihane"'s message of 26 Jan 1996 19:33:30 GMT
-
- In article <4ebaaa$jh6@barnacle.iol.ie> "John D. Hourihane" <hourihaj@iol.ie> writes:
-
- : I am trying to write a function which will return a pointer to a function,
- : but I'm having no luck.
-
- Your problem lies in the declaration of the function.
- (int f(int, int)) *pick(int s);
- It's a very logical attempt but unfortunately not quite right.
- It should have been:
- int (*pick(int s))(int,int);
-
- I would look on the net for a utility called cdecl, it will explain these
- complication declarations for you.
-
- Typedefs are very good for this sort of thing and makes things a lot
- simpler to understand:
-
- typedef int (*FuncPtr)(int, int);
- FuncPtr pick(int s);
-
- Here's your code corrected:
-
- #include <stdio.h>
-
- #define ADD 0
- #define MULTIPLY 1
-
- typedef int (*FuncPtr)(int, int);
-
- FuncPtr pick(int s);
-
- int
- main(void)
- {
- printf("5 + 4 = %d\n", pick(ADD)(5,4));
- printf("5 * 4 = %d\n", pick(MULTIPLY)(5,4));
-
- return 0;
- }
-
- int
- add(int x, int y)
- {
- return x + y;
- }
-
- int
- multiply(int x, int y)
- {
- return x * y;
- }
-
- FuncPtr pick(int s)
- {
- switch (s) {
- case ADD:
- return add;
- case MULITPLY:
- return multiply;
- }
-
- return 0;
- }
-
- Hope this helps
-
- Regards
-
- -A.
- --
- | A.Champion |
-